package com.le.dub.service.impl;



import com.alibaba.fastjson.JSONObject;
import com.le.dub.mobile.Order;
import com.le.dub.mobile.bo.WxOrderBO;
import com.le.dub.service.IWxPayService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.app.model.Transaction;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

@Service
public class WxPayServiceImpl implements IWxPayService {

    @Value("${wx.appid}")
    private String appid;
    //商户号
    @Value("${wx.merchantId}")
    private String merchantId;
    //商户私钥路径
    @Value("${wx.privateKeyPath}")
    private String privateKeyPath;
    //商户证书序列号
    @Value("${wx.merchantSerialNumber}")
    private String merchantSerialNumber;
    //商户APIV3密钥
    @Value("${wx.apiV3key}")
    private String apiV3key;
    //回调地址
    @Value("${wx.notifyUrl}")
    private String notifyUrl;
    public static Config config;
    private     Config getConfig(String merchantId,String privateKeyPath,String merchantSerialNumber ,String apiV3key){
            if(config==null){
                 config= new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)

                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3key)
                        .build();
             }
               return  config;
    }

    @Override
    public Transaction callback(HttpServletRequest request) throws Exception {
        String body = getRequestBodyData(request);
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(request.getHeader("Wechatpay-Serial"))
                .nonce(request.getHeader("Wechatpay-Nonce"))
                .signature(request.getHeader("Wechatpay-Signature"))
                .timestamp(request.getHeader("Wechatpay-Timestamp"))
                .body(body)
                .build();

// 如果已经初始化了 RSAAutoCertificateConfig，可直接使用
// 没有的话，则构造一个


// 初始化 NotificationParser
        NotificationParser parser = new NotificationParser((NotificationConfig) config);
       // 以支付通知回调为例，验签、解密并转换成 Transaction
        Transaction transaction = parser.parse(requestParam, Transaction.class);
          System.out.println("我的订单号" + transaction.getOutTradeNo());
        return transaction;
    }
    @Transactional
    @Override
    public JSONObject createOrder(WxOrderBO order) {
        // 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        Config config= getConfig(merchantId,privateKeyPath,merchantSerialNumber,apiV3key);

        // 构建service
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();

// 跟之前下单示例一样，填充预下单参数
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(order.getAmount());
        request.setAmount(amount);
        request.setAppid(appid);
        request.setMchid(merchantId);
        request.setDescription(order.getDescription());
        request.setNotifyUrl(notifyUrl);
        request.setOutTradeNo(order.getOutTradeNo());
        Payer payer = new Payer();
        payer.setOpenid(order.getOpenId());
        request.setPayer(payer);
// response包含了调起支付所需的所有参数，可直接用于前端调起支付
        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);       // 使用微信扫描 code_url 对应的二维码，即可体验Native支付


        JSONObject jsonObject=new JSONObject();
        jsonObject.put("paySign",response.getPaySign());
        jsonObject.put("appId",response.getAppId());
        jsonObject.put("nonceStr",response.getNonceStr());
        jsonObject.put("timeStamp",response.getTimeStamp());
        jsonObject.put("packageVal",response.getPackageVal());
        jsonObject.put("signType",response.getSignType());
         return jsonObject;
    }

    private String getRequestBodyData(HttpServletRequest request) throws Exception {
        BufferedReader bufferReader = new BufferedReader(request.getReader());
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = bufferReader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}
